package cn.hchaojie.camp.day13;

import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

// 创建一个服务器，接收客户端请求
// ServerSocket
public class Server1 {
	public static void main(String[] args) {
		// 端口不能用1024端口以下的
		ServerSocket server = null;
		Socket socket = null;
		InputStream in = null;
		OutputStream out = null;
		try {
			server = new ServerSocket(6666);
			
			System.out.println("服务器启动了，准备接收连接。。。");
			
			// 接收一个客户端连接
			// 如果有客户端连接，accept会马上返回一个socket对象
			// 如果没有，accept方法会让当前的线程处于阻塞状态
			socket = server.accept();	// socket代表连接上的客户端
			
			System.out.println("连上了一个客户端：" + socket.getInetAddress() + " 端口：" + socket.getPort());
			
			// 开始通信
			in = socket.getInputStream();
			
			while (true) {
				char read = (char) in.read();
				System.out.println(read);
				
				if (read == '8') {
					break;
				}
			}
			
			System.out.println("通信结束。。。");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			closeQuietly(in);
			closeQuietly(out);
			closeQuietly(socket);
			closeQuietly(server);
		}
	}
	
	public static void closeQuietly(Closeable c) {
		if (c != null) {
			try {
				c.close();
			} catch (IOException e) {
			}
		}
	}
}
